package com.holly.unit.deform.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.holly.unit.deform.api.constants.DeformConstants;
import com.holly.unit.deform.entity.DesignFormRoute;
import com.holly.unit.deform.mapper.DeformRouteMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 类描述: 表单设计器 路由服务类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/7 10:36
 */
@Service
public class DeformRouteService extends ServiceImpl<DeformRouteMapper, DesignFormRoute> {

    public DesignFormRoute getEffectiveRoute(String desformCode) {
        LambdaQueryWrapper<DesignFormRoute> queryWrapper = createWrapper(desformCode);
        return super.getOne(queryWrapper);
    }

    private LambdaQueryWrapper<DesignFormRoute> createWrapper(String desformCode) {
        LambdaQueryWrapper<DesignFormRoute> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DesignFormRoute::getDesformCode, desformCode);
        queryWrapper.eq(DesignFormRoute::getStatus, DeformConstants.ROUTE_STATUS_1);
        return queryWrapper;
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean editById(DesignFormRoute designFormRoute) {
        // 如果状态更改为启用，就将其他的设为禁用
        if (DeformConstants.ROUTE_STATUS_1.equals(designFormRoute.getStatus())) {
            DesignFormRoute updateEntity = new DesignFormRoute();
            updateEntity.setStatus(DeformConstants.ROUTE_STATUS_0);
            LambdaQueryWrapper<DesignFormRoute> updateQueryWrapper = createWrapper(designFormRoute);
            super.update(updateEntity, updateQueryWrapper);
        }
        return super.updateById(designFormRoute);
    }

    private LambdaQueryWrapper<DesignFormRoute> createWrapper(DesignFormRoute designFormRoute) {
        LambdaQueryWrapper<DesignFormRoute> updateQueryWrapper = new LambdaQueryWrapper<>();
        updateQueryWrapper.eq(DesignFormRoute::getDesformCode, designFormRoute.getDesformCode());
        updateQueryWrapper.eq(DesignFormRoute::getDesformId, designFormRoute.getDesformId());
        return updateQueryWrapper;
    }

}
